<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 定义售后记录接口
interface AfterSaleRecord {
  afterSaleId: number;
  orderId: string;
  userId: number;
  type: number;
  reason: string;
  status: number;
  createTime: string;
  processTime: string | null;
}

// 表单数据
const selectedNeed = ref('refund')
const reasonText = ref('')
const orderId = ref('ORDER001')
const userId = ref(2)

// 历史售后记录 - 使用明确的类型
const historyList = ref<AfterSaleRecord[]>([])

// 售后类型映射
const afterSaleTypeMap: { [key: string]: number } = {
  refund: 1,
  moneyBack: 2, 
  complaint: 3
}

// 状态映射
const statusMap: { [key: number]: string } = {
  0: '待处理',
  1: '处理中',
  2: '已完成',
  3: '已拒绝'
}

// 类型显示映射
const typeMap: { [key: number]: string } = {
  1: '退货',
  2: '仅退款', 
  3: '举报/投诉'
}

onMounted(() => {
  loadHistory()
})

const loadHistory = async () => {
  try {
    const response = await fetch(`http://localhost:8088/dev/api/afterSale/user/${userId.value}`)
    const result = await response.json()
    
    if (result.success) {
      historyList.value = result.data || []
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
  }
}

const submitForm = async () => {
  if (!orderId.value.trim()) {
    alert('请输入订单号')
    return
  }
  
  if (!reasonText.value.trim()) {
    alert('请输入详细需求')
    return
  }

  const afterSaleData = {
    userId: userId.value,
    orderId: orderId.value.trim(),
    type: afterSaleTypeMap[selectedNeed.value],
    reason: reasonText.value.trim(),
    status: 0,
  }

  try {
    const response = await fetch('http://localhost:8088/dev/api/afterSale/create', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(afterSaleData)
    })

    const result = await response.json()
    
    if (result.success) {
      alert('售后申请提交成功！')
      reasonText.value = ''
      await loadHistory()
    } else {
      alert('提交失败：' + result.message)
    }
  } catch (error) {
    console.error('提交失败:', error)
    alert('网络错误，请稍后重试')
  }
}

const formatTime = (timeStr: string) => {
  if (!timeStr) return '-'
  return new Date(timeStr).toLocaleString('zh-CN')
}

const getStatusClass = (status: number) => {
  switch (status) {
    case 0: return 'status-pending'
    case 1: return 'status-processing'
    case 2: return 'status-completed'
    case 3: return 'status-rejected'
    default: return 'status-unknown'
  }
}
</script>

<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <header class="page-header">
      <h1 class="header-title">📦 售后服务</h1>
      <p class="header-subtitle">为您提供优质的售后支持</p>
    </header>

    <div class="main-content">
      <!-- 左侧申请区域 -->
      <div class="left-section">
        <div class="form-card">
          <div class="card-header">
            <h2>申请售后服务</h2>
            <div class="step-indicator">为您服务</div>
          </div>
          
          <form @submit.prevent="submitForm" class="service-form">
            <!-- 服务类型选择 -->
            <div class="form-group">
              <label class="form-label">服务类型</label>
              <div class="radio-group">
                <label class="radio-item" :class="{ active: selectedNeed === 'refund' }">
                  <input type="radio" v-model="selectedNeed" value="refund" hidden>
                  <div class="radio-content">
                    <span class="radio-icon">🔄</span>
                    <span class="radio-text">退货</span>
                  </div>
                </label>
                
                <label class="radio-item" :class="{ active: selectedNeed === 'moneyBack' }">
                  <input type="radio" v-model="selectedNeed" value="moneyBack" hidden>
                  <div class="radio-content">
                    <span class="radio-icon">💰</span>
                    <span class="radio-text">仅退款</span>
                  </div>
                </label>
                
                <label class="radio-item" :class="{ active: selectedNeed === 'complaint' }">
                  <input type="radio" v-model="selectedNeed" value="complaint" hidden>
                  <div class="radio-content">
                    <span class="radio-icon">⚠️</span>
                    <span class="radio-text">举报投诉</span>
                  </div>
                </label>
              </div>
            </div>

            <!-- 订单信息 -->
            <div class="form-group">
              <label class="form-label">订单序列号</label>
              <div class="input-with-tip">
                <input 
                  type="text" 
                  v-model="orderId" 
                  placeholder="请输入订单号"
                  class="form-input"
                >
              </div>
            </div>

            <!-- 问题描述 -->
            <div class="form-group">
              <label class="form-label">问题描述</label>
              <textarea 
                v-model="reasonText"
                placeholder="请详细描述您遇到的问题，以便我们更好地为您服务..."
                class="form-textarea"
                rows="5"
              ></textarea>
            </div>

            <!-- 提交按钮 -->
            <button type="submit" class="submit-button">
              <span class="button-icon">📨</span>
              提交申请
            </button>
          </form>
        </div>
      </div>

      <!-- 右侧历史记录 -->
      <div class="right-section">
        <div class="history-card">
          <div class="card-header">
            <h2>申请记录</h2>
            <span class="record-count">{{ historyList.length }} 条记录</span>
          </div>
          
          <div class="history-content">
            <div v-if="historyList.length === 0" class="empty-state">
              <div class="empty-icon">📝</div>
              <p>暂无售后记录</p>
              <small>提交申请后，记录将显示在这里</small>
            </div>
            
            <div v-else class="history-list">
              <div 
                v-for="item in historyList" 
                :key="item.afterSaleId" 
                class="history-item"
                :class="getStatusClass(item.status)"
              >
                <div class="item-header">
                  <div class="item-meta">
                    <span class="order-number">订单 {{ item.orderId }}</span>
                    <span class="service-type">{{ typeMap[item.type] || '未知类型' }}</span>
                  </div>
                  <span class="status-badge" :class="getStatusClass(item.status)">
                    {{ statusMap[item.status] || '未知状态' }}
                  </span>
                </div>
                
                <div class="item-reason">
                  {{ item.reason }}
                </div>
                
                <div class="item-footer">
                  <span class="time-info">
                    <span class="time-label">申请时间:</span>
                    {{ formatTime(item.createTime) }}
                  </span>
                  <span v-if="item.processTime" class="time-info">
                    <span class="time-label">处理时间:</span>
                    {{ formatTime(item.processTime) }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-header {
  text-align: center;
  color: white;
  margin-bottom: 30px;
}

.header-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 10px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
}

.main-content {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 30px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 卡片样式 */
.form-card, .history-card {
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
  overflow: hidden;
}

.card-header {
  padding: 25px 30px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-bottom: 1px solid #e1e8ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #2d3748;
  font-size: 1.4rem;
}

.step-indicator {
  background: #4CAF50;
  color: white;
  padding: 5px 12px;
  border-radius: 15px;
  font-size: 0.9rem;
  font-weight: 600;
}

.record-count {
  background: #667eea;
  color: white;
  padding: 5px 12px;
  border-radius: 15px;
  font-size: 0.9rem;
}

/* 表单样式 */
.service-form {
  padding: 30px;
}

.form-group {
  margin-bottom: 25px;
}

.form-label {
  display: block;
  margin-bottom: 12px;
  font-weight: 600;
  color: #2d3748;
  font-size: 1rem;
}

/* 单选按钮组 */
.radio-group {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.radio-item {
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  padding: 20px 15px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f8fafc;
}

.radio-item:hover {
  border-color: #667eea;
  transform: translateY(-2px);
}

.radio-item.active {
  border-color: #667eea;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.radio-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.radio-icon {
  font-size: 1.5rem;
}

.radio-text {
  font-weight: 600;
  font-size: 0.9rem;
}

/* 输入框样式 */
.form-input, .form-textarea {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 10px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: #667eea;
}

.form-textarea {
  resize: vertical;
  min-height: 120px;
}

.input-with-tip {
  position: relative;
}

.input-tip {
  display: block;
  margin-top: 8px;
  font-size: 0.85rem;
  color: #718096;
}

/* 提交按钮 */
.submit-button {
  width: 100%;
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  border: none;
  padding: 16px;
  border-radius: 12px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.submit-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 20px rgba(76, 175, 80, 0.3);
}

/* 历史记录样式 */
.history-content {
  padding: 0;
  max-height: 600px;
  overflow-y: auto;
}

.empty-state {
  padding: 60px 30px;
  text-align: center;
  color: #718096;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 15px;
}

.history-list {
  padding: 20px;
}

.history-item {
  background: #f8fafc;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 15px;
  border-left: 4px solid #667eea;
  transition: transform 0.2s ease;
}

.history-item:hover {
  transform: translateX(5px);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.item-meta {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.order-number {
  font-weight: 600;
  color: #2d3748;
}

.service-type {
  background: #edf2f7;
  color: #4a5568;
  padding: 3px 8px;
  border-radius: 6px;
  font-size: 0.8rem;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 600;
}

.status-pending .status-badge {
  background: #fff3cd;
  color: #856404;
}

.status-processing .status-badge {
  background: #cce7ff;
  color: #004085;
}

.status-completed .status-badge {
  background: #d4edda;
  color: #155724;
}

.status-rejected .status-badge {
  background: #f8d7da;
  color: #721c24;
}

.item-reason {
  color: #4a5568;
  line-height: 1.5;
  margin-bottom: 12px;
}

.item-footer {
  display: flex;
  flex-direction: column;
  gap: 5px;
  font-size: 0.85rem;
}

.time-info {
  color: #718096;
}

.time-label {
  font-weight: 600;
  margin-right: 5px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .radio-group {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .page-container {
    padding: 10px;
  }
  
  .card-header {
    padding: 20px;
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }
  
  .service-form {
    padding: 20px;
  }
}
</style>